﻿using HZY.Framework.Core.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;

namespace HZY.Core.UploadFile;

public class CoreFileStartup : StartupModule<CoreFileStartup>
{
    public override void ConfigureServices(WebApplicationBuilder webApplicationBuilder)
    {
        var services = webApplicationBuilder.Services;

        var fileOption = webApplicationBuilder.Configuration.GetSection(nameof(FileOptions)).Get<FileOptions>() ??
                         throw new ArgumentNullException("配置文件缺少 FileOptions 配置");

        services.AddSingleton(fileOption);

        services.Configure<KestrelServerOptions>(options => { options.Limits.MaxRequestBodySize = fileOption.GetMaxRequestBodySize(); });

        services.Configure<FormOptions>(options => { options.MultipartBodyLengthLimit = fileOption.GetMaxRequestBodySize(); });

        services.AddTransient<IFileManager, FileManager>();
    }

    public override void Configure(WebApplication webApplication)
    {
        var fileOption = webApplication.Services.GetRequiredService<FileOptions>();
        var webHostEnvironment = webApplication.Services.GetRequiredService<IWebHostEnvironment>();

        var filePath = fileOption.GetFilePath(webHostEnvironment.WebRootPath);

        if (!Directory.Exists(filePath))
        {
            Directory.CreateDirectory(filePath);
        }

        //设置静态文件夹映射
        webApplication.UseStaticFiles(new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(filePath),
            RequestPath = fileOption.RequestPath
        });
    }
}